/*******************************************************************************
 * Chatty - Mobile Messaging - J2ME ICQ clone
 * Copyright (C) 2003-11  Chatty Project
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ********************************************************************************
 * File: src/chatty/Answerer.java
 * Version: ###VERSION###  Date: ###DATE###
 * Author(s): R.U.S.H.A.N. aka rn3107
 *******************************************************************************/


package chatty.modules;

import java.io.*;
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

import DrawControls.*;
import DrawControls.text.Parser;

import chatty.*;
import chatty.chat.message.Message;
import chatty.comm.*;
import chatty.io.Storage;
import chatty.ui.*;
import chatty.ui.base.*;
import chatty.ui.form.*;
import chatty.ui.menu.*;
import chatty.util.*;

import protocol.*;

public final class Answerer extends TextList implements FormListener, SelectListener, PopupListener {
    /**
     * 
     * @deprecated 
     */
    private Vector dictionary = new Vector();
    private GraphForm form = new GraphForm("answerer_dictionary", "save", "back", this);
	 
	private int selItem = 0;
    private static final int MENU_EDIT   = 0;
    private static final int MENU_BACK   = 1;
    private static final int MENU_ADD    = 2;
    private static final int MENU_CLEAR  = 3;
    private static final int MENU_DELETE = 4;
	private static final int MENU_ON_OFF = 6;
    
	private static final int FORM_EDIT_QUESTION = 0;
	private static final int FORM_EDIT_ANSWER = 1;
				
    protected MenuModel getMenu() {
        MenuModel menu = new MenuModel(MenuModel.MENU_LEFT);
        menu.clean();
        if (dictionary.size() > 0) {
            menu.addItem("edit",   Chatty.icons.iconAt(Chatty.ICON_EDIT),       MENU_EDIT);
            menu.addItem("delete", Chatty.icons.iconAt(Chatty.ICON_DEL),        MENU_DELETE); 
            menu.addItem("delete_all", 	Chatty.chatIcons.iconAt(Chatty.ICON_CLEAR), MENU_CLEAR);
		}
        menu.addItem("add_new", 	Chatty.icons.iconAt(Chatty.ICON_ADD),       MENU_ADD);
        
		if (Options.getBoolean(Options.OPTION_ANSWERER))
			menu.addItem("answerer_off", Chatty.icons.iconAt(Chatty.ICON_OFF),  MENU_ON_OFF);
		else
			menu.addItem("answerer_on",	Chatty.icons.iconAt(Chatty.ICON_ON),    MENU_ON_OFF);
		
        menu.addItem("back",   		Chatty.icons.iconAt(Chatty.ICON_BACK),	    MENU_BACK);
        menu.setDefaultItemCode(MENU_ADD);
        menu.setActionListener(this);
        return menu;
    }
    
    private Answerer() {
        super(ResBundle.getString("answerer"));
        setMenuCodes(MENU_BACK, MENU_EDIT);
    }
    
    private static final Answerer instance = new Answerer();
    public static Answerer getInstance() {
        return instance;
    }
	
   public void activate() {
        instance.refreshList();
        instance.show();
    }
    
    protected void itemSelected() {
        getMenu().exec(null, MENU_EDIT);
    }
    
    private void refreshList() {
        lock();
        clear();
        int count = dictionary.size();
        for (int i = 0; i < count; ++i) {
            Parser line = createParser(i);
            line.useMinHeight();
            line.addText((String)dictionary.elementAt(i),
                    CanvasEx.THEME_TEXT, FONT_STYLE_PLAIN);
            addPar(line);
        }
        unlock();
    }
    
    public void load() {
        Storage storage = new Storage("chatty-module-answerer");
        try {
            storage.open(false);
            dictionary = storage.loadListOfString();
        } catch (Exception e) {
            // #sijapp cond.if modules_DEBUGLOG is "true" #
            DebugLog.panic("answerer dictionary load", e);
            // #sijapp cond.end#
        }
        storage.close();
		
		DebugLog.println("answerer load: " + dictionary.size() + " items" );
		
		if (0 == dictionary.size()) {
		
           /*dictionary.addElement("Привет=Привет.");
		   dictionary.addElement("Здарова=Даров");
		   dictionary.addElement("Дарова=Даров");
		   dictionary.addElement("Хай=Hi");
		   dictionary.addElement("Как дела=Хорошо, у тебя как?");
		   dictionary.addElement("Спокойной ночи=Карамельных снов!");
		   dictionary.addElement("Приятного=Пасиба!");
		   dictionary.addElement("Приятного аппетита=Пасиба! :-)");
		   dictionary.addElement("Спасибо=На здоровье!");
		   dictionary.addElement(":-Р=;-)");
		   dictionary.addElement(":-)=:-)");*/
		   dictionary.addElement("Hello=Hi. :-)");
		   dictionary.addElement("Hi=H1 :-).");
		   save(); 
        }
    }

    private void save() {
        Storage storage = new Storage("chatty-module-answerer");
        try {
            storage.delete();
            if (0 == dictionary.size()) {
                return;
            }
            storage.open(true);
            storage.saveListOfString(dictionary);
        } catch (Exception e) {
            // #sijapp cond.if modules_DEBUGLOG is "true" #
            DebugLog.panic("answerer dictionary save", e);
            // #sijapp cond.end#
        }
        storage.close();
    }
    
	public void checkMessage(Message message) {
		String msg = message.getText();
		 
        for (int i = 0; i < dictionary.size(); ++i) {
            if (-1 != msg.indexOf(getItemQuestion(i))) {
			
                message.getRcvr().sendMessage(getItemAnswer(i), true);
            }
        }
	}
	private String getItem() {
        return (getSize() == 0)
                ? ""
                : (String)dictionary.elementAt(getCurrTextIndex());
		
    }
    private String getItemQuestion(int index) {
        return (getSize() == 0)
                ? ""
                : Util.explode((String)dictionary.elementAt(index), '=')[0];
		
    }
	private String getItemAnswer(int index) {
        return (getSize() == 0)
                ? ""
                : Util.explode((String)dictionary.elementAt(index), '=')[1];
		
    }
    public void select(Select select, MenuModel model, int cmd) {
        switch (cmd) {
		
            case MENU_EDIT:
				selItem = getCurrTextIndex();
			    form.clearForm();
                form.addTextField(FORM_EDIT_QUESTION, "answerer_question", getItemQuestion(getCurrTextIndex()), 256, TextField.ANY);
				form.addTextField(FORM_EDIT_ANSWER, "answerer_answer", getItemAnswer(getCurrTextIndex()), 256, TextField.ANY);
                form.show();
				break;
                
            case MENU_ADD:
			    dictionary.addElement(" = ");
				setCurrTextIndex(dictionary.size());
				selItem = dictionary.size() - 1;
                form.clearForm();
                form.addTextField(FORM_EDIT_QUESTION, "answerer_question", "", 256, TextField.ANY);
				form.addTextField(FORM_EDIT_ANSWER, "answerer_answer", "", 256, TextField.ANY);
                form.show();
				break;
				
			case MENU_ON_OFF:
				Options.setBoolean(Options.OPTION_ANSWERER, !Options.getBoolean(Options.OPTION_ANSWERER));
				Options.safeSave();
                restore();
				break;
			
            case MENU_BACK:
                back();
                break;
                
            case MENU_DELETE:
                dictionary.removeElementAt(getCurrTextIndex());
                save();
                refreshList();
                restore();
                break;
                
            case MENU_CLEAR:
                PopupWindow.showAttentionBox(ResBundle.getString("clear") + "?", getInstance());
                break;
        }
    }
	
	public void popupAction() {
        dictionary.removeAllElements();
        save();
        back();
    }
	
	/* Command listener */
    public void formAction(GraphForm form, boolean apply) {
        /* Look for back command */
        if (!apply) {
            form.back();
 
            // Look for save command
        } else {
            // Save values, depending on selected option menu item
		    String  item = form.getTextFieldValue(FORM_EDIT_QUESTION) +  "=" + form.getTextFieldValue(FORM_EDIT_ANSWER);
				
			dictionary.setElementAt(item, selItem);
			refreshList();
			restore();
            //form.back();
        }
    }

}